package com.dhcc.bpm.modules.workflow.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.dhcc.bpm.common.annotation.Log;
import com.dhcc.bpm.common.enums.BusinessType;
import com.dhcc.bpm.common.utils.ResResult;
import com.dhcc.bpm.common.utils.ResultAPI;
import com.dhcc.bpm.modules.api.entity.IssueApi;
import com.dhcc.bpm.modules.api.service.IApiService;
import com.dhcc.bpm.modules.api.service.IIssueApiService;
import com.dhcc.bpm.modules.api.vo.ApiVO;
import com.dhcc.bpm.modules.cost.service.ICostRuleService;
import com.dhcc.bpm.modules.cost.vo.CostRuleVO;
import com.dhcc.bpm.modules.orga.controller.AppController;
import com.dhcc.bpm.modules.orga.service.ITestApplyService;
import com.dhcc.bpm.modules.workflow.entity.Approve;
import com.dhcc.bpm.modules.workflow.service.IApproveService;
import com.dhcc.bpm.modules.workflow.vo.ApproveVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.log.annotation.ApiLog;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @ClassName ApproveController
 * @Description 工作流审批表
 * @Author sjm
 * @Date 2020/2/27 0027 13:14
 * @Version V1.0
 * @Copyright: 2020 东华软件 . All rights reserved.
 **/
@RestController
@AllArgsConstructor
@NoArgsConstructor
@RequestMapping("bpm-workflow/approve")
@Api(value = "工作流审批表", tags = "工作流审批表接口")
public class ApproveController extends BladeController {

	private static final Logger log = LoggerFactory.getLogger(ApproveController.class);

    @Value("${workflow.flow-url}")
    private String progressUrl;
    @Value("${bpm.approval.modeType}")
    private String modelType;
    @Value("${bpm.approval.useruid}")
    private String useruid;

    @Autowired
	private IApproveService approveService;
	@Autowired
	private AppController appController;
    @Autowired
	private IApiService apiService;
    @Autowired
	private ICostRuleService costRuleService;
    @Autowired
    private ITestApplyService testApplyService;
	@Autowired
	private IIssueApiService issueApiService;


	/**
	 * @Description 详情
	 * @Author sjm
	 * @Date 9:42 2020/3/3 0003
	 * @param approve
	 * @return org.springblade.core.tool.api.R<com.dhcc.bpm.modules.workflow.entity.Approve>
	 **/
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入approve")
	@ApiLog("工作流审批详情")
	@Log(title = "工作流审批详情",businessType = BusinessType.SELECT)
	public R<Approve> detail(Approve approve) {
		Approve detail = approveService.getOne(Condition.getQueryWrapper(approve));
		return R.data(detail);
	}

	/**
	 * @Description 分页 工作流审批表
	 * @Author sjm
	 * @Date 9:42 2020/3/3 0003
	 * @param approve
	 * @param query
	 * @return org.springblade.core.tool.api.R<com.baomidou.mybatisplus.core.metadata.IPage<com.dhcc.bpm.modules.workflow.entity.Approve>>
	 **/
	@ApiLog("工作流审批分页")
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入approve")
	@Log(title = "工作流审批分页",businessType = BusinessType.SELECT)
	public R<IPage<Approve>> list(Approve approve, Query query) {
		IPage<Approve> pages = approveService.page(Condition.getPage(query), Condition.getQueryWrapper(approve));
		return R.data(pages);
	}

	/**
	 * @Description 自定义分页 工作流审批表
	 * @Author sjm
	 * @Date 9:42 2020/3/3 0003
	 * @param approve
	 * @param query
	 * @return org.springblade.core.tool.api.R<com.baomidou.mybatisplus.core.metadata.IPage<com.dhcc.bpm.modules.workflow.vo.ApproveVO>>
	 **/
	@ApiLog("工作流审批分页")
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入approve")
	@Log(title = "工作流审批分页",businessType = BusinessType.SELECT)
	public R<IPage<ApproveVO>> page(ApproveVO approve, Query query) {
		IPage<ApproveVO> pages = approveService.selectApprovePage(Condition.getPage(query), approve);
		return R.data(pages);
	}

	/**
	 * @Description 新增 工作流审批表
	 * @Author sjm
	 * @Date 9:43 2020/3/3 0003
	 * @param approve
	 * @return org.springblade.core.tool.api.R
	 **/
	@ApiLog("工作流审批新增")
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入approve")
	@Log(title = "工作流审批新增",businessType = BusinessType.UPDATE)
	public R save(@Valid @RequestBody Approve approve) {
		return R.status(approveService.save(approve));
	}

	/**
	 * @Description 修改 工作流审批表
	 * @Author sjm
	 * @Date 9:43 2020/3/3 0003
	 * @param approve
	 * @return org.springblade.core.tool.api.R
	 **/
	@ApiLog("工作流审批修改")
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入approve")
	@Log(title = "工作流审批修改",businessType = BusinessType.UPDATE)
	public R update(@Valid @RequestBody Approve approve) {
		return R.status(approveService.updateById(approve));
	}

	/**
	 * @Description 新增或修改 工作流审批表
	 * @Author sjm
	 * @Date 9:43 2020/3/3 0003
	 * @param approve
	 * @return org.springblade.core.tool.api.R
	 **/
	@ApiLog("工作流审批新增修改")
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入approve")
	@Log(title = "工作流审批新增或修改",businessType = BusinessType.UPDATE)
	public R submit(@Valid @RequestBody Approve approve) {
		return R.status(approveService.saveOrUpdate(approve));
	}

	
	/**
	 * @Description 删除 工作流审批表
	 * @Author sjm
	 * @Date 9:43 2020/3/3 0003
	 * @param ids
	 * @return org.springblade.core.tool.api.R
	 **/
	@ApiLog("工作流审批删除")
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	@Log(title = "工作流审批删除",businessType = BusinessType.DELETE)
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(approveService.deleteLogic(Func.toLongList(ids)));
	}

	/**
	 * @Description 发起审批
	 * @Author sjm
	 * @Date 14:47 2020/2/25 0025
	 * @param approve
	 * @return org.springblade.core.tool.api.R
	 **/
	@ApiLog("发起审批")
	@PostMapping("/commitTask")
	@ApiOperationSupport(order = 6)
	@Log(title = "发起审批",businessType = BusinessType.OTHER)
	@ApiOperation(value = "发起审批", notes = "传入id 和type")
	public R commitTask(@Valid @RequestBody ApproveVO approve) {
		if(approve.getAccount() == null && approve.getRealName() == null){
			BladeUser user = AuthUtil.getUser();
			approve.setAccount(user.getAccount());
			approve.setRealName(user.getNickName());
		}
		//审批类型
		if(approve.getModeType() == null){
			approve.setModeType(modelType);
		}
		//联合办公账号
		if(approve.getUseruid() == null){
			approve.setUseruid(useruid);
		}
        //判断审批类型
       if("1".equals(approve.getModeType())){
            //简单模式
            approve.setModeTypeDesc("简单模式");
        }else{
            //复杂模式
            approve.setModeTypeDesc("复杂模式");
        }
		return approveService.commitTask(approve);
	}


	/**
	 * @Description 产品发布
	 * @Author sjm
	 * @Date 12:43 2020/2/27 0027
	 * @param approve
	 * @return com.dhcc.bpm.common.utils.ResultAPI
	 **/
	@ApiLog("产品发起审批")
	@PostMapping("/commitTaskProduct")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "发起审批", notes = "传入id 和type")
	@Log(title = "发起审批",businessType = BusinessType.OTHER)
	public R commitTaskProduct(@Valid @RequestBody ApproveVO approve) {
        BladeUser user = AuthUtil.getUser();
        approve.setAccount(user.getAccount());
        approve.setRealName(user.getNickName());
		//审批类型
        if(approve.getModeType() == null){
			approve.setModeType(modelType);
		}
        //联合办公账号
        if(approve.getUseruid() == null){
			approve.setUseruid(useruid);
		}
        //判断审批类型
        if("1".equals(approve.getModeType())){
            //简单模式
            approve.setModeTypeDesc("简单模式");
        }else{
            //复杂模式
            approve.setModeTypeDesc("复杂模式");
        }
        return approveService.commitTaskProduct(approve);
	}



	/**
	 * @Description 接受数据
	 * @Author sjm
	 * @Date 9:43 2020/3/3 0003
	 * @param resData
	 * @return com.dhcc.bpm.common.utils.ResultAPI
	 **/
	@ApiLog("接受数据")
	@PostMapping("/refreshData")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "接受数据", notes = "传入approve")
	@Log(title = "接受数据",businessType = BusinessType.OTHER)
	@ResponseBody
	public ResResult refreshData(@Valid @RequestBody String resData) {
		log.info("接收参数 ：" +resData);
		//取Head的值
		JSONObject obj= (JSONObject) JSON.parse(resData);
		JSONObject head= (JSONObject) obj.get("Head");
		//审批结果
		String opinionType = head.getString("opinion_type");
		String isPass = opinionType;
		//审批意见
		String opinion = head.getString("opinion");
		//取body的值
		ResultAPI data = JSONObject.parseObject(resData,ResultAPI.class);
		Object body = data.getBody();
		JSONObject resultStr = (JSONObject) JSONObject.parse(body.toString());
		Long busNo = resultStr.getLong("busNo");
		Long processId = resultStr.getLong("projectID");
		//修改审批表的审批状态
        Approve approve = new Approve();
        approve.setProcessId(processId);
        //查询原数据
		Approve app = approveService.selectApprove(processId);
		approve.setId(app.getId());
		if ("0".equals(opinionType)) {
			//审批通过
			approve.setApprovalStatus(1L);
		}else {
			//审批不通过
			approve.setApprovalStatus(2L);
		}
		//更新数据
		approveService.updateById(approve);
		//处理审批结束后的业务
		ResResult result = null;
		//判断多产品是否全部审批(渠道申请、渠道变更、生产环境、正式上线)
		String type = app.getType();
		if("app".equals(type) || "appChange".equals(type) || "produceapply".equals(type) || "onlineapply".equals(type) ) {
			Approve approve1 = new Approve();
			approve1.setBusNo(app.getBusNo());
			approve1.setType(app.getType());
			QueryWrapper<Approve> queryWrapper = Condition.getQueryWrapper(approve1);
			List<Approve> list = approveService.list(queryWrapper);
			ArrayList<String> list1 = new ArrayList<>();
			if (list.size() > 0) {
				for (Approve datas : list) {
					Long approvalStatus = datas.getApprovalStatus();
					list1.add(String.valueOf(approvalStatus));
				}
				//多产品审批状态集合包括0说明未全部审核完毕
				if (list1.contains("0")) {
					return ResResult.success();
				} else {
					//多产品判断审批是否通过
					Set status = new HashSet(list1);
					if (status.size() == 1) {
						//去重多产品审批结果一样
						String appStatus = list1.get(0);
						if ("1".equals(appStatus)) {
							//通过审批
							opinionType = "1";
						} else if ("2".equals(appStatus)) {
							//通过不审批
							opinionType = "2";
						}
					} else {
						//不通过
						opinionType = "2";
					}
				}
			}
		}else{
		   //其他审批类型  审批结果转化
           if ("0".equals(opinionType)){
               //通过审批
               opinionType = "1";
           }else{
               //不通过
               opinionType = "2";
           }
        }
		//查询实体
		Approve entity = approveService.getById(app.getId());
		log.info("审批实体：" + entity.toString());
		//处理审批结束业务
		result = approveService.refreshData(opinionType,opinion, entity);
		if ("0".equals(isPass)){
			//通过审批
			appController.refreshAppSecret();
		}
        return result;
	}

	@ApiLog("判断api是否收费")
	@PostMapping("/apiCostRealease")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "判断api是否收费", notes = "传入id 和type")
	@Log(title = "判断api是否收费",businessType = BusinessType.OTHER)
	public R ApiCostRealease(@Valid @RequestBody ApproveVO approve) {
		R r = new R();
		List<Long> ids = Func.toLongList(approve.getIds());
		List<ApiVO> apiList = apiService.getListByIds(ids);
		List<CostRuleVO> costRuleList = costRuleService.getListByIds(ids);
			int i = 0;
			for (ApiVO apiVO : apiList) {
				if (apiVO.getIsCost() == 1) {
					//此API是收费API
					i++;
				}
			}
			if (i > 0) {
				if (costRuleList != null && costRuleList.size() > 0) {
					int j = 0;
                    for (Long apiId : ids) {
                        for (CostRuleVO costRule : costRuleList) {
                            if (Long.parseLong(costRule.getApiId()) == apiId) {
                                j++;
                            }
                            continue;
                        }
                    }

					if(j == i){
						//判断全部收费设置完毕
						commitTask(approve);
						return R.status(true);
					}else{
						r.setSuccess(false);
						r.setCode(267);
						r.setMsg("发布失败，请先对收费的API设置收费规则!");
						return r;
					}
				} else {
					r.setSuccess(false);
					r.setCode(267);
					r.setMsg("发布失败，请先对收费的API设置收费规则!");
					return r;
				}
			}else{
				//免费直接发布
				commitTask(approve);
				return R.status(true);
			}
    }

	/**
	 * @Description 单个api发布收费规则
	 * @Author sjm
	 * @Date 17:07 2020/3/23 0023
	 * @param costRule
	 * @return org.springblade.core.tool.api.R
	 **/
	@ApiLog("单个api发布收费规则")
	@PostMapping("/submitCostApi")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入costRule")
	@Log(title = "单个api发布收费规则", businessType = BusinessType.UPDATE)
	public R submitCostApi(@Valid @RequestBody CostRuleVO costRule) {
		costRule.setRefreshFlag(0);
		if (costRuleService.saveOrUpdate(costRule)){
			ApproveVO approve = new ApproveVO();
			approve.setIds(costRule.getIds());
			approve.setType(costRule.getType());
			approve.setAppType(costRule.getAppType());
			approve.setModeType(costRule.getModeType());
			approve.setUseruid(costRule.getUseruid());
			return ApiCostRealease(approve);
		}else{
			return R.status(false);
		}
	}

	/**
	 * @Description 查看审批进度
	 * @Author sjm
	 * @Date 18:17 2020/3/26 0026
	 * @param approve
	 * @return org.springblade.core.tool.api.R
	 **/
	@PostMapping("/approveProgress")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "查看审批进度", notes = "id")
	@ApiLog("查看审批进度")
	@Log(title = "查看审批进度", businessType = BusinessType.SELECT)
	public R approveProgress(@Valid @RequestBody ApproveVO approve) {
		R r = new R();
		String type = approve.getType();
		Long busNo = approve.getBusNo();
		Long productId = approve.getProductId();
		String url = null;
		Long processId = null;
		Approve appros = null;
		//多产品查询审批进度
		if("app".equals(type) || "appChange".equals(type) || "produceapply".equals(type) || "onlineapply".equals(type) ) {
			appros = approveService.getApproByProdAppId(busNo,productId);
		}else if("api".equals(type)){
			IssueApi issueApi = new IssueApi();
			issueApi.setApiId(busNo);
			IssueApi api = issueApiService.selectByApiId(busNo);
			if(api == null){
				r.setCode(267);
				r.setSuccess(false);
				r.setMsg("该条信息待审核!");
				return r;
			}
			appros = approveService.getApproById(api.getId());

		}else{
			appros = approveService.getApproById(approve.getBusNo());
		}
		if(appros == null){
			r.setCode(267);
			r.setSuccess(false);
			r.setMsg("该条信息待审核!");
			return r;
		}
		processId = appros.getProcessId();
		url = progressUrl + "/procmanage/flowmanage?viewmode=999&ProcinstId=" + processId;
		return R.data(url);
	}
}
